const fs = window.require("fs");
const { dialog } = window.require("electron").remote;

export default function uploadImage(state, { jud, fn, that }) {
  let imgBufferList = [];
  let path;

  //选择图片
  path = dialog.showOpenDialogSync({
    filters: [{ name: "Images", extensions: ["jpg", "png", "gif", "jpeg"] }],
    properties: jud ? ["multiSelections"] : [], //判断是不是多选
  });

  if (path) {
    //创建目录
    // try {
    //   let stats = fs.statSync(that.__filePath + "/developPageImage");
    //   if (stats.isDirectory())
    //     fs.mkdirSync(that.__filePath + "/developPageImage", { recursive: true });
    // } catch (error) {
    //   console.error(error);
    //   fn([], error);
    // }

    //图片复制到指定文件夹下
    path.forEach((item) => {
      try {
        let data = fs.readFileSync(item);
        let dirname = `${
          that.__filePath
        }/developPageImage/${new Date().getTime()}.${
          item
            .split("\\")
            .reverse()[0]
            .split(".")[1]
        }`;
        fs.writeFileSync(dirname, data);
        imgBufferList.push({
          blob: URL.createObjectURL(new Blob([data])),
          src: dirname,
        });
      } catch (error) {
        console.error(error);
        return fn([], error);
      }
    });

    return fn(imgBufferList);
  }

  return fn([]);
}
